<template>
  <div class="main-box scroll">
    <TreeFilter
      label="name"
      title="组织机构"
      search-label="组织机构名称"
      :data="treeFilterData"
      :default-value="initParam.org_id"
      :show-node-contextmenu="true"
      @change="changeTreeFilter"
      @node-contextmenu="rightClick"
    >
    </TreeFilter>
    <!-- 树形控件右键组件 -->
    <div v-show="menuShow" class="tree_rightmenu" :style="{ ...rightMenu }">
      <el-menu class="el-menu-vertical-demo" @select="selectMenuNode">
        <el-menu-item
          id="menuitem"
          index="1"
          style="font-size: 12px"
          v-if="treeFilterData[0] && curMenuNode.id !== treeFilterData[0].children[0].id && thisPermission.org_create"
          @click="openOrgDialog('addOrEditTreeRef', true)"
        >
          <template #title>
            <span>新增本级</span>
          </template>
        </el-menu-item>
        <el-menu-item
          id="menuitem"
          index="2"
          style="font-size: 12px"
          @click="openOrgDialog('addOrEditTreeRef', true)"
          v-if="thisPermission.org_create"
        >
          <template #title>
            <span>新增下级</span>
          </template>
        </el-menu-item>
        <el-menu-item
          id="menuitem"
          index="3"
          style="font-size: 12px"
          @click="openOrgDialog('addOrEditTreeRef', false)"
          v-if="thisPermission.org_update"
        >
          <template #title>
            <span>编辑</span>
          </template>
        </el-menu-item>
        <el-menu-item
          index="4"
          style="font-size: 12px"
          v-if="treeFilterData[0] && curMenuNode.id !== treeFilterData[0].children[0].id && thisPermission.org_delete"
          @click="deleteOrg()"
        >
          <template #title>
            <span>删 除</span>
          </template>
        </el-menu-item>
      </el-menu>
    </div>
    <div class="table-box">
      <ProTable
        ref="proTable"
        title="用户列表"
        highlight-current-row
        :columns="columns"
        :request-api="getUserList"
        :pagination="true"
        :show-summary="false"
        :init-param="initParam"
        :indent="20"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 4, xl: 4 }"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <el-button :icon="Plus" type="primary" @click="openDialog('addOrEditUserRef', 0)" v-if="thisPermission.create">
            新建
          </el-button>
          <el-button
            type="danger"
            @click="deleteAccount(scope.selectedList)"
            v-if="thisPermission.delete"
            :disabled="!(scope.selectedList.length > 0)"
          >
            删除
          </el-button>
          <el-button
            type="primary"
            @click="disableAccount(scope.selectedList, '禁用')"
            v-if="thisPermission.disable"
            :disabled="!(scope.selectedList.length > 0)"
          >
            禁用
          </el-button>
          <el-button
            type="primary"
            @click="disableAccount(scope.selectedList, '启用')"
            v-if="thisPermission.enable"
            :disabled="!(scope.selectedList.length > 0)"
          >
            启用
          </el-button>
        </template>
        <!--Expand 表格操作-->
        <template #enable="scope">
          <el-badge
            is-dot
            class="item"
            :color="scope.row.enable ? '#43CF7C' : '#696969'"
            :offset="[-5, 8]"
            :badge-style="{ width: '6px', height: '6px' }"
          ></el-badge>
          <span class="text">{{ scope.row.enable ? "启用" : "禁用" }}</span>
          <span></span>
        </template>
        <template #operation="scope">
          <el-button type="primary" link @click="openDialog('addOrEditUserRef', scope.row.id)" v-if="thisPermission.update">
            编辑
          </el-button>
          <el-button type="primary" link @click="deleteAccount([scope.row])" v-if="thisPermission.delete">删除</el-button>
          <el-button
            type="primary"
            link
            @click="disableAccount([scope.row], scope.row.enable ? '禁用' : '启用')"
            v-if="thisPermission.disable && thisPermission.enable"
            >{{ scope.row.enable ? "禁用" : "启用" }}
          </el-button>
        </template>
      </ProTable>
      <modalAddOrEdit ref="addOrEditUserRef" @refresh="refresh" />
      <modalTreeAddOrEdit ref="addOrEditTreeRef" @refresh="refreshOrgTree" />
    </div>
  </div>
</template>

<script setup lang="ts" name="userManagement">
import TreeFilter from "@/components/TreeFilter/index.vue";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { User } from "@/api/interface/userManagement";
import modalAddOrEdit from "@/views/sysManagement/user_management/component/modal_add_or_edit.vue";
import modalTreeAddOrEdit from "@/views/sysManagement/user_management/component/modal_tree_add_or_edit.vue";
import { getUserList, getTreeList, userTerminate, userDisable, userEnable, treeDelete } from "@/api/modules/userManagement";
import { computed, onMounted, reactive, ref } from "vue";
import { useHandleData } from "@/hooks/useHandleData";
import { Plus } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import { useAuthStore } from "@/stores/modules/auth";
const route = useRoute();
const authStore = useAuthStore();
const thisPermission = computed(() => authStore.permissionListGet[route.name as string] || {});
// ProTable 实例
const proTable = ref<ProTableInstance>();

// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  { type: "selection", width: 80 },
  { type: "index", label: "#", width: 80 },
  { prop: "username", label: "用户账号", search: { el: "input" }, width: 100 },
  { prop: "uniq_code", label: "用户工号", search: { el: "input" }, width: 120 },
  { prop: "name", label: "用户姓名", search: { el: "input" }, width: 100 },
  { prop: "type.verbose", label: "用户类型", width: 120 },
  { prop: "mobile_phone", label: "手机号码", search: { el: "input" }, width: 150 },
  { prop: "office_phone", label: "办公电话", width: 150 },
  { prop: "email", label: "电子邮箱", search: { el: "input" }, minWidth: 150 },
  { prop: "enable", label: "状态", width: 120 },
  { prop: "operation", label: "操作", fixed: "right", minWidth: 180 }
]);
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ org_id: "" });
// 获取 treeFilter 数据
// 当 proTable 的 requestAuto 属性为 false，不会自动请求表格数据，等待 treeFilter 数据回来之后，更改 initParam.org_id 的值，才会触发请求 proTable 数据
const treeFilterData = ref<any>([]);
const getTreeFilter = async () => {
  const { data } = await getTreeList();
  treeFilterData.value = [{ id: "", name: "全部", children: [data] }];
};
// 组织树右键点击事件
const curMenuNode = ref<any>("");
const menuShow = ref<boolean>(false);
const rightMenu = ref<any>({});
const rightClick = (e, data) => {
  curMenuNode.value = data;
  menuShow.value = false; // 先把模态框关死，目的是 第二次或者第n次右键鼠标的时候 它默认的是true
  if (data.id) {
    menuShow.value = true;
    e.preventDefault(); //关闭浏览器右键默认事件
    rightMenu.value = { top: e.pageY + "px", left: e.pageX + "px" };
    document.addEventListener("click", ev => {
      // ev.stopImmediatePropagation()
      if (ev.target !== document.querySelector(".el-menu-item.is-active")) {
        foo();
      }
    });
  }
};
const foo = () => {
  // 取消鼠标监听事件 菜单栏
  menuShow.value = false;
  document.removeEventListener("click", foo); // 关掉监听，
};
let curLevel = 1;
const selectMenuNode = data => {
  curLevel = data;
};
const changeTreeFilter = (data: string) => {
  proTable.value!.pageable.page = 1;
  initParam.org_id = data;
  foo();
};
// 删除用户
const deleteAccount = async (params: any[]) => {
  const toDoList: string[] = [];
  const notToDoList: string[] = [];
  const ids: number[] = params.map(item => {
    if (item.id) {
      toDoList.push(item.username);
    } else {
      notToDoList.push(item.username);
    }
    return item.id;
  });
  console.log(ids);
  await useHandleData(userTerminate, { ids: ids }, ["删除", "用户"], toDoList, notToDoList);
  proTable.value?.getTableList();
};
// 用户禁用
const disableAccount = async (params: any[], opName) => {
  const toDoList: string[] = [];
  const notToDoList: string[] = [];
  let ids: number[] = params.map(item => {
    if ((item.enable && opName === "禁用") || (!item.enable && opName === "启用")) {
      toDoList.push(item.username);
      return item.id;
    } else {
      notToDoList.push(item.username);
    }
  });
  ids = ids.filter(item => item);
  if (opName === "禁用") await useHandleData(userDisable, { ids: ids }, [opName, "用户"], toDoList, notToDoList);
  if (opName === "启用") await useHandleData(userEnable, { ids: ids }, [opName, "用户"], toDoList, notToDoList);
  proTable.value?.getTableList();
  proTable.value?.clearSelection();
};
// 新建编辑用户
const addOrEditUserRef = ref<InstanceType<typeof modalAddOrEdit> | null>(null);
const openDialog = (ref: string, id: number = 0) => {
  if (ref == "addOrEditUserRef") addOrEditUserRef.value?.openDialog(id);
};
// 新建编辑组织机构
const addOrEditTreeRef = ref<InstanceType<typeof modalTreeAddOrEdit> | null>(null);
const openOrgDialog = (ref: string, isAdd: boolean) => {
  if (ref == "addOrEditTreeRef") addOrEditTreeRef.value?.openDialog(curMenuNode.value, isAdd, curLevel);
};
// 删除组织
const deleteOrg = () => {
  ElMessageBox.confirm("是否确定删除所选组织机构？", "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const res = await treeDelete(curMenuNode.value.id);
    if (res) {
      ElMessage({
        type: "success",
        message: "删除成功"
      });
    }
  });
};
const refresh = () => {
  proTable.value?.getTableList();
};
const refreshOrgTree = () => {
  getTreeFilter();
};
onMounted(async () => {
  getTreeFilter();
});
</script>

<style lang="scss" scoped>
.main-box {
  flex-direction: row;
  height: 100%;
  &-left {
    display: flex;
    width: 250px;
    margin-right: 10px;
    background: #ffffff;
    border-radius: 4px;
    box-shadow: 0 0 8px 0 #e6e6e6;
  }
  &-main {
    display: flex;
    flex: 1;
    flex-direction: column;
    height: 100%;
  }
}
.tree_rightmenu {
  position: fixed;
  z-index: 1000;
  width: 120px;
  border: 1px solid rgb(0 0 0 / 15%);
  box-shadow: 0 6px 12px rgb(0 0 0 / 17.5%);
}
</style>
